package com.example.interview.Tree;

import java.util.LinkedList;
import java.util.Queue;

// 定义二叉树节点类
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    public TreeNode(int val) {
        this.val = val;
    }
}

// 求二叉树高度的函数
public class BinaryTreeHeight {

    public int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        } else {
            int leftHeight = getHeight(root.left);
            int rightHeight = getHeight(root.right);

            // 返回左右子树中较大的高度，并加上根节点的高度1
            return Math.max(leftHeight, rightHeight) + 1;
        }
    }
    //层序遍历
    public int getHeight2(TreeNode root) {
        if (root == null) {
            return 0;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int height = 0;

        while (!queue.isEmpty()) {
            int levelSize = queue.size(); // 当前层的节点数量

            // 遍历当前层的所有节点，并将它们的子节点加入队列
            for (int i = 0; i < levelSize; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }

            // 每遍历完一层，高度加一
            height++;
        }

        return height;
    }
    public static void main(String[] args) {
        // 创建一个示例二叉树
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);

        // 计算二叉树的高度
        BinaryTreeHeight btHeight = new BinaryTreeHeight();
        int height = btHeight.getHeight(root);
        System.out.println("Binary Tree Height: " + height); // 输出高度
    }
}
